package by.sjc.grsu.security;

import by.sjc.grsu.dao.repositiory.AccountDao;
import by.sjc.grsu.model.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Z on 09.09.14.
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private AccountDao accountDao;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        Account account = accountDao.loadAccountByEmail(s);
        if (account==null)
            throw (new UsernameNotFoundException("user "+s+" not found"));

        List authorities = new ArrayList();
        authorities.add( new GrantedAuthorityImpl("ROLE_"+account.getType().toString()) );

        CustomUserDetails customUserDetails = new CustomUserDetails(
                account.getEmail(),
                account.getPassword(),
                authorities
        );
        customUserDetails.setAccount(account);
        return customUserDetails;
    }
}
